#include "gifplayer.h"

GifPlayer::GifPlayer(const QString &gifPath, QWidget *parent)
    : QLabel(parent)
{
    // -------- 1. 用 QMovie 预解 GIF ---------------------------------
    QMovie mv(gifPath);
    mv.setCacheMode(QMovie::CacheAll);
    if (!mv.isValid()) {
        qWarning() << "GIF invalid:" << gifPath;
        return;
    }

    mv.start();                       // 必须 start 才能 jumpToFrame
    mv.jumpToFrame(0);                // 初始化

    int n = mv.frameCount();          // -1 表示未知，循环直到 jumpToFrame=false
    for (int i = 0; n < 0 || i < n; ++i) {
        if (!mv.jumpToFrame(i)) break;
        frames_  << mv.currentImage();
        delays_  << mv.nextFrameDelay();      // ms
        if (n < 0 && mv.loopCount() == 1 && i > 0 &&
            mv.currentImage() == frames_.first()) {     // 部分 GIF 帧数未知，用重复检测
            frames_.pop_back();
            delays_.pop_back();
            break;
        }
    }
    mv.stop();

    if (frames_.isEmpty()) {
        qWarning() << "GIF contains no frames.";
        return;
    }
    // -------- 2. 连接计时器 ----------------------------------------
    connect(&timer_, &QTimer::timeout, this, &GifPlayer::showNextFrame);
    setPixmap(QPixmap::fromImage(frames_.first()));
}

void GifPlayer::play()
{
    if (frames_.isEmpty()) return;
    idx_ = 0;
    setPixmap(QPixmap::fromImage(frames_[idx_]));
    timer_.start(delays_[idx_]);
}

void GifPlayer::pause()
{
    timer_.stop();
}

void GifPlayer::seek(int frameIndex)
{
    if (frames_.isEmpty()) return;
    idx_ = frameIndex % frames_.size();
    setPixmap(QPixmap::fromImage(frames_[idx_]));
    timer_.start(delays_[idx_]);
}

void GifPlayer::showNextFrame()
{
    if (frames_.isEmpty()) return;
    idx_ = (idx_ + 1) % frames_.size();
    setPixmap(QPixmap::fromImage(frames_[idx_]));
    timer_.start(delays_[idx_]);          // 用下一帧自己的时长重启定时器
}
